//
//  YSHelp.m
//  writemall
//
//  Created by mac on 2021/8/3.
//  Copyright © 2021 p.write.mall. All rights reserved.
//
#import "YSHelp.h"
 
#import <CoreText/CoreText.h>

@implementation YSHelp



+ (void)setButton:(UIButton *)button text:(NSString *)text textColor:(UIColor *)color font:(UIFont *)font
{
    [button setTitle:text forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font=font;
}

+ (void)setLabel:(UILabel *)label text:(NSString *)text textColor:(UIColor *)color font:(UIFont *)font
{
    label.text=text;
    label.font=font;
    label.textColor=color;
}


/**  快捷获取View*/
+ (UIView *)getViewSuperView:(id)superView rect:(CGRect)rect
{
    UIView *view=[[UIView alloc]initWithFrame:rect];
    [(UIView *)superView addSubview:view];
    return view;
}


/**  快捷获取button*/
+ (XSButton *)getButtonSuperView:(id)superView rect:(CGRect)rect text:(NSString *)text textColor:(UIColor *)color font:(UIFont *)font
{
    XSButton *button=[XSButton buttonWithType:UIButtonTypeCustom];
    [(UIView *)superView addSubview:button];
    button.frame=rect;
    [button setTitle:text forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font=font;
    return button;
}

/**  快捷获取label*/
+ (UILabel *)getLabelSuperView:(id)superView rect:(CGRect)rect text:(NSString *)text textColor:(UIColor *)color font:(UIFont *)font
{
    UILabel *label=[[UILabel alloc]initWithFrame:rect];
    [(UIView *)superView addSubview:label];
    label.text=text;
    label.font=font;
    label.textColor=color;
    return label;
}

/**  快捷获取imageview*/
+ (UIImageView *)getImageViewSuperView:(id)superView rect:(CGRect)rect image:(UIImage *)image
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:rect];
    [(UIView *)superView addSubview:imageView];
    imageView.image=image;
    return imageView;
}


+ (void)setLineSpacingWithLabel:(UILabel *)label text:(NSString*)text lineSpacing:(CGFloat)lineSpacing {
    if (lineSpacing < 0.01 || !text) {
        label.text = text;
        return;
    }
    
    /**  这里要注意系统的行差值  根据字体大小来定  最终lineSpacing值=（实际大小-这个系统差值）字体差值大致 10-2 11-2 12-2  13-2.5 14-3 15-3 16-3 17-3 18-3.5 19-4 20-4  例如实际间距为10 字体大小为15  这里的linespacing值为（10-3）=7 */
    
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
//    [attributedString addAttribute:NSFontAttributeName value:label.font range:NSMakeRange(0, [text length])];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setLineBreakMode:label.lineBreakMode];
    [paragraphStyle setAlignment:label.textAlignment];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    
    label.attributedText = attributedString;
}

/**  计算有行间距的label的高度  这里也要注意系统间距差问题*/
+ (CGFloat)heightOfText:(NSString*)text heightWithFont:(UIFont *)font width:(CGFloat)width lineSpacing:(CGFloat)lineSpacing
{
    if(![YSHelp judgeStringNull:text])
    {
        return 0;
    }
    
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, MAXFLOAT)];
    label.font = font;
    label.numberOfLines = 0;
    [YSHelp setLineSpacingWithLabel:label text:text lineSpacing:lineSpacing];
    [label sizeToFit];
    CGFloat aHeight=label.frame.size.height;
    CGFloat newHeight = [YSHelp inHeightOfText:@"ceshi" heightWithFont:font width:width lineSpacing:lineSpacing];
    if(aHeight==newHeight)//只有一行的情况
    {
        aHeight=aHeight-lineSpacing;
    }
    return aHeight;
}



//这里new一个方法出来计算
+ (CGFloat)inHeightOfText:(NSString*)text heightWithFont:(UIFont *)font width:(CGFloat)width lineSpacing:(CGFloat)lineSpacing
{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, MAXFLOAT)];
    label.font = font;
    label.numberOfLines = 0;
    [YSHelp setLineSpacingWithLabel:label text:text lineSpacing:lineSpacing];
    [label sizeToFit];
    return label.frame.size.height;
}


+(CGFloat)widthOfString:(NSString *)string font:(UIFont *)font height:(CGFloat)height
{
    CGRect rect;
    NSDictionary * dict=[NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
    rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    return rect.size.width;
}

+(CGFloat)heightOfString:(NSString *)string font:(UIFont *)font width:(CGFloat)width
{
    CGRect bounds;
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:parameterDict context:nil];
    return bounds.size.height;
}

/**  计算富文本文字长度*/
+ (CGFloat)widthOfAtrributeString:(NSMutableAttributedString *)string  height:(CGFloat)height
{
    CGSize attSize = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return attSize.width;
}

/**  计算富文本文字高度*/
+ (CGFloat)heightOfAtrributeString:(NSMutableAttributedString *)string  width:(CGFloat)width
{
    CGSize attSize = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return attSize.height;
}




/**  根据时间格式来转化dateString 普通格式 yyyyMMdd HHmmss*/
+ (NSString *)formateDate:(NSString *)dateString dateFormatterString:(NSString *)formatterString
{
    //     常用日期结构：
    //     yyyy-MM-dd HH:mm:ss.SSS
    //     yyyy-MM-dd HH:mm:ss
    //     yyyy-MM-dd
    //     MM dd yyyy
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:formatterString];//选择需要的格式
    
    
    
    /////  将需要转换的时间转换成 NSDate 对象
    NSDate * needFormatDate;
    if(dateString.length==13)
    {
        needFormatDate = [NSDate dateWithTimeIntervalSince1970:[dateString doubleValue]/1000];
    }
    else if (dateString.length==10)
    {
        needFormatDate = [NSDate dateWithTimeIntervalSince1970:[dateString doubleValue]];
    }
    
    
    
//    //早晚8个小时操作  早 -interval  晚 interal
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate: needFormatDate];
//    needFormatDate = [needFormatDate dateByAddingTimeInterval: -interval];
    
    
    NSString *dateStr = @"";
    dateStr = [dateFormatter stringFromDate:needFormatDate];
    return dateStr;
    
    
}


+ (NSString *)compareTime:(NSString *)dateString{
    //     常用日期结构：
    //     yyyy-MM-dd HH:mm:ss.SSS
    //     yyyy-MM-dd HH:mm:ss
    //     yyyy-MM-dd
    //     MM dd yyyy
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//选择需要的格式
    
    NSDate * nowDate = [NSDate date];
    
    /////  将需要转换的时间转换成 NSDate 对象
    NSDate * needFormatDate;
    if(dateString.length==13)
    {
        needFormatDate = [NSDate dateWithTimeIntervalSince1970:[dateString doubleValue]/1000];
    }
    else if (dateString.length==10)
    {
        needFormatDate = [NSDate dateWithTimeIntervalSince1970:[dateString doubleValue]];
    }
    /////  取当前时间和转换时间两个日期对象的时间间隔
    /////  这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:  typedef double NSTimeInterval;
    NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
    
    //// 再然后，把间隔的秒数折算成天数和小时数：
    
    NSString *dateStr = @"";
    
    if (time<=60) {  //// 1分钟以内的
        dateStr = @"刚刚";
    }else if(time<=60*60){  ////  一个小时以内的
        
        int mins = time/60;
        dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
        
    }else if(time<=3*60*60*24){   //// 在三天内的
        
        [dateFormatter setDateFormat:@"dd"];
        NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
        NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
        NSInteger integer=[now_yMd integerValue]-[need_yMd integerValue];
        
        [dateFormatter setDateFormat:@"HH:mm:ss"];
        if ([need_yMd isEqualToString:now_yMd]) {
            //// 在同一天
            dateStr = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:needFormatDate]];
        }else if(integer==1||(integer<0&&[now_yMd integerValue]==1))
        {
            ////  昨天
            dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
        }
        else if (integer==2||(integer<0&&[now_yMd integerValue]==2))
        {
            ////  前天
            dateStr = [NSString stringWithFormat:@"前天 %@",[dateFormatter stringFromDate:needFormatDate]];
        }
        else
        {
            [dateFormatter setDateFormat:@"MM-dd"];
            dateStr = [dateFormatter stringFromDate:needFormatDate];
        }
    }
    else {
        
        [dateFormatter setDateFormat:@"yyyy"];
        NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
        NSString *nowYear = [dateFormatter stringFromDate:nowDate];
        
        if ([yearStr isEqualToString:nowYear]) {
            ////  在同一年
            [dateFormatter setDateFormat:@"MM-dd"];
            dateStr = [dateFormatter stringFromDate:needFormatDate];
        }else{
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            dateStr = [dateFormatter stringFromDate:needFormatDate];
        }
    }
    
    return dateStr;
    
}


+ (CGFloat)getDistanceWithFirstln:(double)firstln andFirstlt:(double)firstlt andSecondln:(double)secondln andSecondlt:(double)secondlt
{
    //1、苹果自带的
    //     CLLocation *firstLoc = [[CLLocation alloc] initWithLatitude: firstlt longitude: firstln];
    //
    //     CLLocation *secondLoc =[[CLLocation alloc] initWithLatitude: secondlt longitude: secondln];
    //
    //     CLLocationDistance distance = [firstLoc distanceFromLocation:secondLoc]/1000;
    
    //     DWLog(@"firstln==%f\n firstlt==%f\n secondln==%f\n secondlt==%f",firstln,firstlt,secondln,secondlt);
    
    
    double dd = M_PI/180;
    double x1=firstlt*dd,x2=secondlt*dd;
    double y1=firstln*dd,y2=secondln*dd;
    double R = 6378137;
    double distance = (2*R*asin(sqrt(2-2*cos(x1)*cos(x2)*cos(y1-y2) - 2*sin(x1)*sin(x2))/2));
    //km  返回
    return  distance/1000;
    
    //返回 m
    //     return   distance;
    
}


//获取当前view所在试图控制器
+ (UIViewController *)viewGetViewController:(UIView *)aView
{
    for(UIView *next=[aView superview];next;next=next.superview)
    {
        UIResponder *nextResponder=[next nextResponder];
        if([nextResponder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

/**  获取当前正在显示的ViewController*/
+ (UIViewController *)getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
    
}



+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}





+ (NSString *)getNowDateWithDateIndexAt:(NSInteger)dateNum
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSString *year = [NSString stringWithFormat:@"%ld",[dateComponent year]];
    NSString *month = [NSString stringWithFormat:@"%ld",[dateComponent month]];
    NSString *day = [NSString stringWithFormat:@"%ld",[dateComponent day]];
    NSString *hour = [NSString stringWithFormat:@"%ld",[dateComponent hour]];
    NSString *minute = [NSString stringWithFormat:@"%ld",[dateComponent minute]];
    NSString *second = [NSString stringWithFormat:@"%ld",[dateComponent second]];
    NSArray *dataArr=@[year,month,day,hour,minute,second];
    return dataArr[dateNum];
}




/** 获取当前时间(时分秒格式)*/
+ (NSString *)getNowDate
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSString *year = [NSString stringWithFormat:@"%ld",[dateComponent year]];
    NSString *month = [NSString stringWithFormat:@"%02ld",[dateComponent month]];
    NSString *day = [NSString stringWithFormat:@"%02ld",[dateComponent day]];
    NSString *hour = [NSString stringWithFormat:@"%02ld",[dateComponent hour]];
    NSString *minute = [NSString stringWithFormat:@"%02ld",[dateComponent minute]];
    NSString *second = [NSString stringWithFormat:@"%02ld",[dateComponent second]];
    return [NSString stringWithFormat:@"%@-%@-%@ %@:%@:%@",year,month,day,hour,minute,second];
}




/** 获取当前时间(可选格式)*/
+ (NSString *)getNowDateWithType:(NSInteger)type
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSString *year = [NSString stringWithFormat:@"%ld",[dateComponent year]];
    NSString *month = [NSString stringWithFormat:@"%02ld",[dateComponent month]];
    NSString *day = [NSString stringWithFormat:@"%02ld",[dateComponent day]];
    NSString *hour = [NSString stringWithFormat:@"%02ld",[dateComponent hour]];
    NSString *minute = [NSString stringWithFormat:@"%02ld",[dateComponent minute]];
    NSString *second = [NSString stringWithFormat:@"%02ld",[dateComponent second]];
    NSString *dateStr = @"";
    switch (type) {//设置目标时间字符串的格式
        case 1:
            dateStr = year;
            break;
        case 2:
            dateStr = [NSString stringWithFormat:@"%@-%@", year,month];
            break;
        case 3:
            dateStr = [NSString stringWithFormat:@"%@-%@-%@", year,month,day];
            break;
        case 4:
            dateStr = [NSString stringWithFormat:@"%@-%@-%@ %@", year,month,day,hour];
            break;
        case 5:
            dateStr = [NSString stringWithFormat:@"%@-%@-%@ %@:%@", year,month,day,hour,minute];
            break;
        case 6:
            dateStr = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:%@", year,month,day,hour,minute,second];
            break;
            
        default:
            break;
    }
    
    
    return dateStr;
}


//判断字符是否为空 返回YES则不为空
+ (BOOL)judgeStringNull:(NSString *)string
{
    if([string isEqualToString:@""]||[string isEqualToString:@"<null>"]||[string isEqualToString:@"(null)"]||!string)
    {
        return NO;
    }
    return YES;
}


/**  转换空字符串为 @"" 格式*/
+ (NSString *)formatNullString:(NSString *)string
{
    if(![YSHelp judgeStringNull:[NSString stringWithFormat:@"%@",string]])
    {
        return @"";
    }
    return [NSString stringWithFormat:@"%@",string];
}


//正则判断手机号格式
+ (BOOL)valiMobile:(NSString *)mobile
{
    
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }
    return YES;
    
    
//    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
//    if (mobile.length != 11)
//    {
//        return NO;
//    }else{
//        /**
//         * 移动号段正则表达式
//         */
//        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
//        /**
//         * 联通号段正则表达式
//         */
//        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
//        /**
//         * 电信号段正则表达式
//         */
//        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
//        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
//        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
//        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
//        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
//        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
//        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
//
//        if (isMatch1 || isMatch2 || isMatch3) {
//            return YES;
//        }else{
//            return NO;
//        }
//    }
}




/** 处理图片防止旋转90度*/
+ (UIImage *)solveImg:(UIImage *)image
{
    if (image.imageOrientation == UIImageOrientationUp)
    {
        return image;
    }
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    [image drawInRect:(CGRect){0, 0, image.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return normalizedImage;
}


/** 将数组元素排序*/
+ (void)rankArray:(NSMutableArray *)muArr littleToBig:(BOOL)big
{
    [muArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSString *a = (NSString *)obj1;
        NSString *b = (NSString *)obj2;
        
        int aNum = [a intValue];
        int bNum = [b intValue];
        
        if(big)//升序
        {
            if (aNum > bNum) {
                return NSOrderedDescending;
            }
            else if (aNum < bNum){
                return NSOrderedAscending;
            }
            else {
                return NSOrderedSame;
            }
        }
        else//降序
        {
            if (aNum < bNum) {
                return NSOrderedDescending;
            }
            else if (aNum > bNum){
                return NSOrderedAscending;
            }
            else {
                return NSOrderedSame;
            }
        }
    }];
    
}

/** 比较两个时间 后比前 返回值1大 0相等  -1小  type 6最大年月日时分秒  1最小 年*/
+ (NSInteger)compareDate:(NSString*)dateOne withDate:(NSString*)dateTwo formatType:(NSInteger)timeType
{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    
    switch (timeType) {
        case 1:
            [df setDateFormat:@"yyyy"];
            break;
        case 2:
            [df setDateFormat:@"yyyy-MM"];
            break;
        case 3:
            [df setDateFormat:@"yyyy-MM-dd"];
            break;
        case 4:
            [df setDateFormat:@"yyyy-MM-dd HH"];
            break;
        case 5:
            [df setDateFormat:@"yyyy-MM-dd HH:mm"];
            break;
        case 6:
            [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            break;
        default:
            break;
    }
    
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:dateOne];
    dt2 = [df dateFromString:dateTwo];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date2比date1大
        case NSOrderedAscending: ci=1; break;
            //date2比date1小
        case NSOrderedDescending: ci=-1; break;
            //date2=date1
        case NSOrderedSame: ci=0; break;
        default:  break;
    }
    return ci;
}



/**  计算中英文混合字符的长度  中文-2字符  数字英文-1字符*/
+ (NSInteger)getStringLength:(NSString *)strTemp
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* da = [strTemp dataUsingEncoding:enc];
    return ([da length]+1)/2;
}



/**  字符转UFT8*/
+ (NSString *)UTF8StringWithString:(NSString *)string
{
    NSString *newStr = nil;
    newStr = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if(QYIOS9>=9.0)
    {
         newStr = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    return newStr;
}

/**  UTF8转字符*/
+ (NSString *)stringWithUTF8String:(NSString *)UTF8String
{
    NSString *newStr = nil;
    newStr = [UTF8String stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return newStr;
}



/**  获取label的行数（数组长度即为行数 每个元素为每行显示的内容）*/
+ (NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label{
    NSString *text = [label text];
    if(!text)
    {
        return @[];
    }
    UIFont *font = [label font];
    CGRect rect = [label frame];
    
    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
    CFRelease(myFont);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = (NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge  CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [text substringWithRange:range];
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
        [linesArray addObject:lineString];
    }
    
    CGPathRelease(path);
    CFRelease( frame );
    CFRelease(frameSetter);
    return (NSArray *)linesArray;
}


/**  获取一个在总字符串中设备某段字符的富文本格式*/
+ (NSMutableAttributedString *)getAttrStrWithAllStr:(NSString *)allStr  attrStr:(NSString *)attrStr font:(UIFont *)font  color:(UIColor *)color
{
    NSMutableAttributedString *muStr = [[NSMutableAttributedString alloc]initWithString:allStr];
    NSRange range = [allStr rangeOfString:attrStr];
    if(range.location != NSNotFound)
    {
        if(color)
        {
            //字体颜色
            [muStr addAttribute:NSForegroundColorAttributeName
             
                          value:color
             
                          range:range];
        }
        
        if(font)
        {
            //字体大小
            [muStr addAttribute:NSFontAttributeName
             
                          value:font
             
                          range:range];
        }
    }
    return muStr;
}




#pragma mark - 输入中文
/*
 ** 输入中文
 */
+ (BOOL) deptNameInputShouldChineseWithstring:(NSString *)inputString
{
    NSString *regex = @"[\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:inputString]) {
        return YES;
    }
    return NO;
}



#pragma mark - 判断全数字：
/*
 ** 判断全数字：
 */
+ (BOOL)isAllNumberWithstring:(NSString *)inputString
{
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:inputString]) {
        return NO;
    }
    return YES;
}



#pragma mark - 判断全字母：
/*
 ** 判断全字母：
 */
+ (BOOL) deptPassInputShouldAlphaWithstring:(NSString *)inputString

{
    NSString *regex =@"[a-zA-Z]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:inputString]) {
        return YES;
    }
    return NO;
}



#pragma mark - 判断仅输入字母或数字：
/*
 ** 判断仅输入字母或数字：
 */
+ (BOOL) deptIdInputShouldAlphaNumWithstring:(NSString *)inputString

{
    
    NSString *regex =@"[a-zA-Z0-9]*";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    if ([pred evaluateWithObject:inputString]) {
        
        return YES;
        
    }
    
    return NO;
    
}
//*  判断用户输入的密码是否符合规范，符合规范的密码要求：
//   1. 长度大于8位
//   2. 密码中必须同时包含数字和字母
+(BOOL)isPassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 8){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}
//*  判断用户输入的密码是否符合规范，符合规范的密码要求：
//   1. 长度大于6位
//   2. 密码中必须同时包含数字和字母
+(BOOL)isPass6_18WordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

+(UIImage *)imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{

    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;

    CGFloat width = imageSize.width;

    CGFloat height = imageSize.height;

    CGFloat targetWidth = size.width;

    CGFloat targetHeight = size.height;

    CGFloat scaleFactor = 0.0;

    CGFloat scaledWidth = targetWidth;

    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);

        if(CGSizeEqualToSize(imageSize, size) == NO){

        CGFloat widthFactor = targetWidth / width;

        CGFloat heightFactor = targetHeight / height;

        if(widthFactor > heightFactor){

        scaleFactor = widthFactor;

        }

    else{

    scaleFactor = heightFactor;

    }

    scaledWidth = width * scaleFactor;

    scaledHeight = height * scaleFactor;

    if(widthFactor > heightFactor){

    thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;

    }else if(widthFactor < heightFactor){

    thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;

    }

    }

UIGraphicsBeginImageContext(size);

CGRect thumbnailRect = CGRectZero;

thumbnailRect.origin = thumbnailPoint;

thumbnailRect.size.width = scaledWidth;

thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();

if(newImage == nil){

NSLog(@"scale image fail");

}

UIGraphicsEndImageContext();
return newImage;

}

#pragma mark - 校验是否是图片
//原理就是检查文件的buffer，从头部找到类型相关的字段，然后和iOS支持的UTI类型进行比较，进而确定是否为图片类型。这个思路可以扩展到所有文件类型的检测
+ (BOOL)isImageSource:(NSURL*)URL {
    CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)URL, NULL);

    NSString *UTI = (__bridge NSString*)CGImageSourceGetType(source);

    CFRelease(source);

    CFArrayRef mySourceTypes = CGImageSourceCopyTypeIdentifiers();

    NSArray *array = (__bridge NSArray*)mySourceTypes;

    CFRelease(mySourceTypes);

    return [array containsObject:UTI];

}

+ (BOOL)isUrlAddress:(NSString*)url{

    NSString*reg =@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";

    NSPredicate*urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];

    return [urlPredicate evaluateWithObject:url];

}

#pragma mark 简单验证身份证
+ (BOOL)simpleIDCardVerification:(NSString *)string {
     if(string.length < 15) {
        return NO;
    }
    NSString *regex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF  MATCHES %@",regex];
    return [pre evaluateWithObject: string];
}
#pragma mark 精确验证15或18位身份证
+ (BOOL)accurateIDCardWithFifteenOrEighteen:(NSString *)string {
    if(string.length != 15 && string.length != 18) {
        return NO;
    }
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSInteger length = string.length;
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    NSString *valueStart2 = [string substringToIndex:2];
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return false;
    }
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [string substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:string
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, string.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            year = [string substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:string
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, string.length)];
            
            if(numberofMatch >0) {
                int S = ([string substringWithRange:NSMakeRange(0,1)].intValue + [string substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([string substringWithRange:NSMakeRange(1,1)].intValue + [string substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([string substringWithRange:NSMakeRange(2,1)].intValue + [string substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([string substringWithRange:NSMakeRange(3,1)].intValue + [string substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([string substringWithRange:NSMakeRange(4,1)].intValue + [string substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([string substringWithRange:NSMakeRange(5,1)].intValue + [string substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([string substringWithRange:NSMakeRange(6,1)].intValue + [string substringWithRange:NSMakeRange(16,1)].intValue) *2 + [string substringWithRange:NSMakeRange(7,1)].intValue *1 + [string substringWithRange:NSMakeRange(8,1)].intValue *6 + [string substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[string substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }
}
#pragma mark 精确验证18位身份证
+ (BOOL) accurateIDCardWithEighteen:(NSString *)string {
    if (string.length!=18) {
        return NO;
    }
    //校验格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    BOOL flag = [identityCardPredicate evaluateWithObject:string];
    if (!flag) {
        return flag;
    }else {
        NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
        NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
        NSInteger idCardWiSum = 0;
        for(int i = 0;i < 17;i++){
            NSInteger subStrIndex = [[string substringWithRange:NSMakeRange(i, 1)] integerValue];
            NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
            idCardWiSum+= subStrIndex * idCardWiIndex;
        }
        NSInteger idCardMod=idCardWiSum%11;
        NSString * idCardLast= [string substringWithRange:NSMakeRange(17, 1)];
        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        if(idCardMod==2){
            if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]){
                return YES;
            }else{
                return NO;
            }
        }else{
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]){
                return YES;
            }else{
                return NO;
            }
        }
    }
}


/**
 *  doc文档转换html方法
 * fileData   从本地读取的doc文档数据流
 * lastFileNamestr doc文档名不包含后缀
 *
 *
 **/
#pragma mark 解析docx 或者 doc 文档数据
+ (void)getHtmlDataWith:(NSData *)fileData withFileName:(NSString *)lastFileNamestr succeed:(void (^)(id data,NSDictionary *errord))resultbk{
    
    NSLog(@"API_userWechatQqParserWord-lastFileNamestr===%@\n",lastFileNamestr);
    
//    
//    XSWeakSelf;
//    if([fileData isKindOfClass:[NSNull class]]||fileData==nil){
//        
//        
////        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
////        [SVProgressHUD showErrorWithStatus:@"读取数据失败"];
//        
//        if([lastFileNamestr isKindOfClass:[NSNull class]]||lastFileNamestr==nil||lastFileNamestr.length==0){
//            lastFileNamestr = [NSString new];
//        }
//        
////        NSData *data = [[@"" encodeUrl] dataUsingEncoding:NSUTF8StringEncoding];
////        data = [data gzippedData];
////        // 加密成Base64形式的NSData
////        NSData *base64Data = [data base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//        // 加密成Base64形式的NSString
////        NSString *base64String = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//        
////        [[NSNotificationCenter defaultCenter] postNotificationName:@"openOtherSourceHtml" object:nil userInfo:@{@"html":base64Data,@"name":lastFileNamestr}];
////        dispatch_async(dispatch_get_main_queue(), ^{
////            [weakSelf dismissViewControllerAnimated:YES completion:nil];
////        });
//        resultbk(@{@"data":@{}},@{@"error":@"读取数据失败"});
//        return;
//    }
//    
////    [MBProgressHUD showTipMessageInView:@"文档解析中..."];
//    
//    
//    [[XLNetWorkManager shareInstance] upload:API_userWechatQqParserWord parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        [formData appendPartWithFileData:fileData name:@"file" fileName:lastFileNamestr mimeType:@"image/png"];
//    } success:^(id  _Nonnull responseObject) {
//        
////        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
//        NSLog(@"API_userWechatQqParserWord===%@\n",responseObject);
//        if ([responseObject[@"returncode"] integerValue] == 0) {
////            weakSelf.htmlDictironary = responseObject;
////            [weakSelf serverWithDictData:responseObject];
//            resultbk(@{@"data":responseObject},nil);
//        }
//        else{
////            [MBProgressHUD showTipMessageInWindow:@"解析错误，请稍后重试！"];
//            resultbk(@{@"data":@{}},@{@"error":@"解析错误，请稍后重试！"});
//        }
//    } failure:^(NSError * _Nonnull error) {
////        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
////        [MBProgressHUD showTipMessageInWindow:error.description];
//        resultbk(@{@"data":@{}},@{@"error":@"解析错误，请稍后重试！"});
//        NSLog(@"API_userWechatQqParserWord--error==%@\n",error.description);
//    }];
}


/**
 *  调用doc文档转换html 方法后进行解压缩
 * dictData   调用doc文档转换html方法后返回的数据
 * filePathStr  原始doc文档路径
 *
 *
 **/
+ (void)serverWithDictData:(NSDictionary *)dictData withFilePath:(NSString *)filePathStr succeed:(void (^)(id data,NSDictionary *errord))resultbk{
    
    
    NSString *lastFileName;
    NSArray *lastFileNameArr = [filePathStr componentsSeparatedByString:@"/"];
    if(lastFileNameArr.count>0){
        lastFileName = lastFileNameArr.lastObject;
    }
    if(kStringIsEmpty(lastFileName)){
        lastFileName = [NSString getNowTimeTimeWithHaoMiao];
    }

    if([dictData[@"data"] isKindOfClass:[NSArray class]]){
        NSArray *resultHtmlArrary = dictData[@"data"];
        NSString *resultHtml = resultHtmlArrary.firstObject;

        NSData *data234 = [[NSData alloc] initWithBase64EncodedString:resultHtml options:NSDataBase64DecodingIgnoreUnknownCharacters];

        NSString *string234 =[[NSString alloc] initWithData:data234 encoding:NSUTF8StringEncoding];

        NSLog(@"string234==%@\n",string234);
        XSWeakSelf;
        if(kStringIsEmpty(string234)){
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            [MBProgressHUD showTipMessageInWindow:@"数据解析异常，请稍后重试!"];
    //        });
            
            resultbk(@{@"data":@{}},@{@"error":@"数据解析异常，请稍后重试!"});
        }
        else{
            
            
    //        NSData *data=[[NSData alloc]initWithBase64EncodedString:self.docUnit.content options:0];
    //        NSData *contentData =  [data gunzippedData];
    //        NSString *contentHtml = [[NSString alloc]initWithData:contentData encoding:NSUTF8StringEncoding];
            
    //        NSData *data = [[string234 encodeUrl] dataUsingEncoding:NSUTF8StringEncoding];
    //        data = [data gzippedData];
    //        // 加密成Base64形式的NSData
    //        NSData *base64Data = [data base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    //        // 加密成Base64形式的NSString
    ////        NSString *base64String = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
            
            NSString *tempHtmlStr = [string234 zipHtml];
            
    //        [[NSNotificationCenter defaultCenter] postNotificationName:@"openOtherSourceHtml" object:nil userInfo:@{@"html":tempHtmlStr,@"name":lastFileName}];
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            [weakSelf dismissViewControllerAnimated:YES completion:nil];
    //        });
            
            resultbk(@{@"data":@{@"html":tempHtmlStr,@"name":lastFileName}},nil);
        }
    }
    else{
        resultbk(@{@"data":@{}},@{@"error":@"数据解析异常，请稍后重试!"});
    }
    
}


+ (void)wqWriteData:(NSString *)contentString withFileName:(NSString *)fNameStr{
    
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
    NSString *date =  [formatter stringFromDate:[NSDate date]];
    NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@", date];


    NSFileManager *fileManager = [NSFileManager defaultManager]; //创建文件管理器
//    NSString *tempPath = NSTemporaryDirectory();    //获得临时文件夹路径
    
    //写入沙盒Documents
    NSArray *pathsDocument = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [pathsDocument objectAtIndex:0];
    NSString *tempPath = [documentsDirectory stringByAppendingPathComponent:@"wqoplgdir"];
    
    // 判断文件夹是否存在
    BOOL folderExists = [fileManager fileExistsAtPath:tempPath];
    // 如果文件夹不存在，就创建文件夹
    if (!folderExists) {
        // 创建文件夹
        NSError *error = nil;
        BOOL success = [fileManager createDirectoryAtPath:tempPath
                                withIntermediateDirectories:YES // 创建中间缺少的目录
                                                 attributes:nil
                                                      error:&error];
        if (!success) {
            // 处理错误
            NSLog(@"创建文件夹失败: %@", [error localizedDescription]);
        }
    }


    NSString *tempPath00 =  [NSString stringWithFormat:@"%@_%@.txt",fNameStr,timeLocal];//[NSString getCurrentFormatTimes]
    NSString *tempFile = [tempPath stringByAppendingPathComponent:tempPath00]; //获得文件全路径
    if (![fileManager fileExistsAtPath:tempFile]) {
        [fileManager createFileAtPath:tempFile contents:nil attributes:nil];  //如果文件不存在就创建一个
    }

    NSString * tempstr = [NSString stringWithFormat:@"%@",contentString];

    NSMutableData *writer = [[NSMutableData alloc] init];   //创建缓冲区
    [writer appendData:[tempstr dataUsingEncoding:NSUTF8StringEncoding]]; //将数据写入缓冲区
    [writer writeToFile:tempFile atomically:YES];   //将缓冲数据写入文件
}


// 设置缓存数据，并设置1天后过期
+ (void)setwqUniCacheData:(id)data {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDate *now = [NSDate date];
    NSDate *expirationDate = [now dateByAddingTimeInterval:24 * 60 * 60]; // 加上24小时（60秒*60分钟*24小时）
    [userDefaults setObject:data forKey:@"wqUniCacheData"];
    [userDefaults setObject:expirationDate forKey:@"wqUniExpirationDate"];
    [userDefaults synchronize]; // 确保数据同步到disk
}
 
// 获取缓存数据
+ (id)getwqUniCacheData {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDate *now = [NSDate date];
    NSDate *expirationDate = [userDefaults objectForKey:@"wqUniExpirationDate"];
    id data = [userDefaults objectForKey:@"wqUniCacheData"];
    
    // 检查数据是否过期
    if (expirationDate == nil || [now compare:expirationDate] == NSOrderedDescending) {
        // 数据已过期，返回nil或重新获取数据
        return nil;
    }
    
    // 数据未过期，返回缓存数据
    return data;
}

+ (void)wqWriteData:(NSString *)contentString withFileName:(NSString *)fNameStr isOpenLog:(BOOL)isOpenLg{
    
    if(isOpenLg){
        
        NSFileManager *fileManager = [NSFileManager defaultManager]; //创建文件管理器
        
        // NSString *tempPath = NSTemporaryDirectory();    //获得临时文件夹路径
        //写入沙盒Documents
        NSArray *pathsDocument = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [pathsDocument objectAtIndex:0];
        NSString *tempPath = [documentsDirectory stringByAppendingPathComponent:@"wqoplgdir"];
        
        // 判断文件夹是否存在
        BOOL folderExists = [fileManager fileExistsAtPath:tempPath];
        // 如果文件夹不存在，就创建文件夹
        if (!folderExists) {
            // 创建文件夹
            NSError *error = nil;
            BOOL success = [fileManager createDirectoryAtPath:tempPath
                                    withIntermediateDirectories:YES // 创建中间缺少的目录
                                                     attributes:nil
                                                          error:&error];
            if (!success) {
                // 处理错误
                NSLog(@"创建文件夹失败: %@", [error localizedDescription]);
            }
        }
        
        NSString *wqClearTemporaryDirectoryFileStr = [self getwqUniCacheData];
        if(wqClearTemporaryDirectoryFileStr==nil){
            [self setwqUniCacheData:@"wqClearTemporaryDirectoryFile"];
            [self wqUniDeleteDirectoryContents:tempPath];
        }
        
        NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
        [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
        NSString *date =  [formatter stringFromDate:[NSDate date]];
        NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@", date];


        
        

        NSString *tempPath00 =  [NSString stringWithFormat:@"%@_%@.txt",fNameStr,timeLocal];//[NSString getCurrentFormatTimes]
        NSString *tempFile = [tempPath stringByAppendingPathComponent:tempPath00]; //获得文件全路径
        if (![fileManager fileExistsAtPath:tempFile]) {
            [fileManager createFileAtPath:tempFile contents:nil attributes:nil];  //如果文件不存在就创建一个
        }

        NSString * tempstr = [NSString stringWithFormat:@"%@",contentString];

        NSMutableData *writer = [[NSMutableData alloc] init];   //创建缓冲区
        [writer appendData:[tempstr dataUsingEncoding:NSUTF8StringEncoding]]; //将数据写入缓冲区
        [writer writeToFile:tempFile atomically:YES];   //将缓冲数据写入文件
        
        
        
    }
    
    
}
//删除目录下的所有文件包括目录
+ (void)wqUniDeleteDirectoryContents:(NSString *)directory {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:directory error:&error];
    
    if (!fileList) {
        //NSLog(@"Error reading directory: %@", [error localizedDescription]);
        return;
    }
    
    for (NSString *file in fileList) {
        NSString *filePath = [directory stringByAppendingPathComponent:file];
        BOOL removeResult = [fileManager removeItemAtPath:filePath error:&error];
        
//        if (!removeResult) {
//            NSLog(@"Error deleting file: %@", [error localizedDescription]);
//        }
    }
}

#pragma mark - 获取文件名不包含  .后缀
/**
 * 传入@"path/to/your/file.txt";
 *  返回 file
 **/
+ (NSString *)getUrlStringFileName:(NSString *)filePath{
    
    
//    NSString *filePath = @"path/to/your/file.txt";
    NSString *fileName = [filePath lastPathComponent];
    // 移除扩展名
    fileName = [fileName stringByDeletingPathExtension];
     // 输出 file
    //NSLog(@"FileName without extension: %@", fileName);
    
    
    
//        // 从路径中获得完整的文件名（带后缀）
//        NSString *exestr55 = [filePath lastPathComponent];
//    XSLog(@"exestr55==%@\n",exestr55);
    
    

//        NSString *filePathStr = [filePath lastPathComponent];
//        // 获得文件名（不带后缀）
//        NSString *filePathStrHouZui = [filePathStr stringByDeletingPathExtension];
//    XSLog(@"filePathStrHouZui==%@\n",filePathStrHouZui);

    
    
//    ////    获得文件的后缀名（不带'.'）
//            NSString *exestr77 =[filePath pathExtension];
//    //    XSLog(@"exestr77==%@\n",exestr77);
    
    return fileName;
}

#pragma mark - 替换文件名中的特殊字符为_ 中文也会被替换
+ (NSString *)wqUniReplaceInvalidCharacters:(NSString *)originalFileName{
    
//    NSString *originalFileName = @"my file#$@%^&*()!?!@#$%^&*()_+<>?.txt";
//    NSString *newFileName = [self wqUniReplaceInvalidCharacters:originalFileName];
//    // 输出 my_file__________________________.txt
//    NSLog(@"newFileName:--%@--", newFileName);
    NSString *regexString = @"[^a-zA-Z0-9._-]"; // 非法字符正则表达式
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:nil];
    NSString *modifiedFileName = [regex stringByReplacingMatchesInString:originalFileName options:0 range:NSMakeRange(0, originalFileName.length) withTemplate:@"_"];

    return modifiedFileName;
}
#pragma mark - 替换文件名中的特殊字符为_ 中文不会被替换(.也会被替换)
+ (NSString *)wqUniReplaceInvalidCharactersNotContainChinese:(NSString *)originalFileName{
    
//    NSString *resStr =[self wqUniReplaceInvalidCharacters:@"my我的而文件34536wertre file#$@%^&*()!?!@#$%^&*()_+<>?.txt"];
//    NSLog(@"resStr:--%@--", resStr);
    // 输出 resStr:--my我的而文件34536wertrefiletxt--
    
    NSString *regex = @"[^a-zA-Z0-9\u4e00-\u9fa5]";
    return [originalFileName stringByReplacingOccurrencesOfString:regex withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, originalFileName.length)];
}

#pragma mark 把HEIC|HEIF图片转成PNG图片
+(NSData *)convertHEICImageToPNG:(UIImage *)image {
    
    //  UIImage *imggg = [[UIImage alloc] initWithData:data];
    // 如果图片已经是PNG格式，则直接返回原数据
    if (UIImagePNGRepresentation(image) != nil) {
        return UIImagePNGRepresentation(image);
    }
    
    // 如果图片是HEIC格式，则转换为PNG
    return UIImagePNGRepresentation(image);
    
    
//    NSData *origdata = [NSData dataWithContentsOfFile:originalFilePath];
//    NSData *data;
//    if([srcTypeStr isEqualToString:@"heic"]||[srcTypeStr isEqualToString:@"heif"]){
//        CIImage *ciImage = [CIImage imageWithData:origdata];
//        CIContext *context = [CIContext context];
//        data = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
//    }
//    else{
//        data = origdata;
//    }
}

#pragma mark 把旋转的图片转成到竖屏视图
//按照UIImageOrientation的定义，利用矩阵自定义实现对应的变换；
+(UIImage *)wqUniTransformImage:(UIImage *)aImage

{
    //UIImage *imggg = [[UIImage alloc] initWithData:data];
    //typedef enum
    //
    //{
    //
    //UIImageOrientationUp,            // default orientation
    //
    //UIImageOrientationDown,          // 180 deg rotation
    //
    //UIImageOrientationLeft,          // 90 deg CCW
    //
    //UIImageOrientationRight,        // 90 deg CW
    //
    //UIImageOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip
    //
    //UIImageOrientationDownMirrored,  // horizontal flip
    //
    //UIImageOrientationLeftMirrored,  // vertical flip
    //
    //UIImageOrientationRightMirrored, // vertical flip
    //
    //} UIImageOrientation;

    //按照UIImageOrientation的定义，利用矩阵自定义实现对应的变换；
    CGImageRef imgRef = aImage.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);

    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;

    CGRect bounds = CGRectMake(0, 0, width, height);

    CGFloat scaleRatio = 1;

    CGFloat boundHeight;

    UIImageOrientation orient = aImage.imageOrientation;

    switch(orient)//UIImageOrientationLeftMirrored

    {

        case UIImageOrientationUp:

            transform = CGAffineTransformIdentity;

            break;

        case UIImageOrientationUpMirrored:

            transform = CGAffineTransformMakeTranslation(width, 0.0);

            transform = CGAffineTransformScale(transform, -1.0, 1.0); //沿y轴向左翻

            break;

        case UIImageOrientationDown:

            transform = CGAffineTransformMakeTranslation(width, height);

            transform = CGAffineTransformRotate(transform, M_PI);

            break;

        case UIImageOrientationDownMirrored:

            transform = CGAffineTransformMakeTranslation(0.0, height);

            transform = CGAffineTransformScale(transform, 1.0, -1.0);

            break;

        case UIImageOrientationLeft:

            boundHeight = bounds.size.height;

            bounds.size.height = bounds.size.width;

            bounds.size.width = boundHeight;

            transform = CGAffineTransformMakeTranslation(0.0, width);

            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);

            break;

        case UIImageOrientationLeftMirrored:

            boundHeight = bounds.size.height;

            bounds.size.height = bounds.size.width;

            bounds.size.width = boundHeight;

            transform = CGAffineTransformMakeTranslation(height, width);

            transform = CGAffineTransformScale(transform, -1.0, 1.0);

            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);

            break;

        case UIImageOrientationRight: //EXIF = 8

            boundHeight = bounds.size.height;

            bounds.size.height = bounds.size.width;

            bounds.size.width = boundHeight;

            transform = CGAffineTransformMakeTranslation(height, 0.0);

            transform = CGAffineTransformRotate(transform, M_PI / 2.0);

            break;

        case UIImageOrientationRightMirrored:

            boundHeight = bounds.size.height;

            bounds.size.height = bounds.size.width;

            bounds.size.width = boundHeight;

            transform = CGAffineTransformMakeScale(-1.0, 1.0);

            transform = CGAffineTransformRotate(transform, M_PI / 2.0);

            break;

        default:

        [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

    }

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {

        CGContextScaleCTM(context, -scaleRatio, scaleRatio);

        CGContextTranslateCTM(context, -height, 0);

    }

    else {

        CGContextScaleCTM(context, scaleRatio, -scaleRatio);

        CGContextTranslateCTM(context, 0, -height);

    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);

    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return imageCopy;

}



+ (UIImage *)xsCreateShadowImage{
    
    CGFloat myBorderViewW = kScreenW-80.0;
    CGFloat myBorderViewH = 50.0;
    CGFloat myBorderViewX = (kScreenW-myBorderViewW)*0.5;
    CGFloat myBorderViewY = 190.0;
    
    UIView *myBorderView = [[UIView alloc] initWithFrame:CGRectMake(myBorderViewX, myBorderViewY, myBorderViewW, myBorderViewH)];
    UIColor *tempfriendImgButtonW = [UIColor whiteColor];
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, myBorderViewW, myBorderViewH);
    gradientLayer.startPoint = CGPointMake(1.0,0.5);
    gradientLayer.endPoint = CGPointMake(0.0,0.5);
    //gradientLayer.locations = @[@(0.5), @(0.0)];
    gradientLayer.colors = @[(id)COLOR_HEX(0xA098DA).CGColor,
                             (id)COLOR_HEX(0xD1BBAA).CGColor,
                             (id)COLOR_HEX(0xF1D38A).CGColor];
    [myBorderView.layer addSublayer:gradientLayer];
    myBorderView.layer.cornerRadius = myBorderViewH*0.5+0.1;
    myBorderView.layer.masksToBounds = YES;

    
    CGFloat myBorderViewTopX = 3.0;
    CGFloat myBorderViewTopY = 3.0;
    CGFloat myBorderViewTopW = myBorderView.frame.size.width-myBorderViewTopX*2.0;
    CGFloat myBorderViewTopH = myBorderView.frame.size.height-myBorderViewTopY*2.0;
    
    UIView *myBorderViewTop = [[UIView alloc] initWithFrame:CGRectMake(myBorderViewTopX, myBorderViewTopY, myBorderViewTopW, myBorderViewTopH)];
    myBorderViewTop.backgroundColor = [UIColor blackColor];
    myBorderViewTop.layer.cornerRadius = myBorderViewTopH*0.5+0.1;
    myBorderViewTop.layer.masksToBounds = YES;
    [myBorderView addSubview:myBorderViewTop];

    
    
    //UIImage *xsFinalImg = [self imageFromView:myBorderView];
    
    
    
//    UIImageView *homeBtnImageView = [[UIImageView alloc] init];
//    homeBtnImageView.backgroundColor  =  UIColor.clearColor;
//    homeBtnImageView.image = xsFinalImg;
//    homeBtnImageView.userInteractionEnabled = NO;
//    [self.view addSubview:homeBtnImageView];
//    homeBtnImageView.frame = CGRectMake(myBorderViewX, 450, myBorderViewW, 45);
    
    return [self imageFromView:myBorderView];
}

+ (UIImage *)imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    view.layer.cornerRadius = view.bounds.size.height*0.5+0.01;
    view.layer.masksToBounds = YES;
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}


/**
 * 并返回公共目录
 */
#pragma mark 移动文件到uniapp公共目录
+ (NSString *)xsMoveVedioToPublickDirWithOriginalString:(NSString *)originalStr{
    // withGoalFileDirStr:(NSString *)goalFileDirStr

    return [YSHelp bossIPMoveVedioToPublickDirWithOriginalStr:originalStr];
}

/**
 * 传入 文件数据fData   跟文件名
 *  返回写入数据的路径
 */
+ (NSString *)bossIpWriteImageData:(NSData *)fData withFileName:(NSString *)fileNameStr{
    
    
    
//        NSString *goalFileDirStr = @"/Pandora/apps/__UNI__7F36DC7/www/xsLBVedioDir/";
//
       // NSString *fileNameStr = [filePathStr lastPathComponent];// 包含后缀
    
    
    //     NSArray *cachePath= NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //     NSString *cacheDir = [cachePath objectAtIndex:0];
    
        NSString *tempString = NSTemporaryDirectory();
    //[NSString stringWithFormat:@"%@/xsBossVideos/%@",tempString,fileNameStr]
         NSString *tempVedioPath = [NSString stringWithFormat:@"%@/xsBossVideos/",tempString];
        //[self wqWriteData:[NSString stringWithFormat:@"tempVedioPath==%@",tempVedioPath] withFileName:@"tempVedioPath"];
    
    
       // NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
//        //
//        NSString * originalFilePath = originalStr;
//
//        NSString * goalFilePath = [docsdir stringByAppendingPathComponent:goalFileDirStr];//将需要创建的串拼接到后面
//
//        [self wqWriteData:[NSString stringWithFormat:@"originalFilePath==%@      goalFilePath==%@",originalFilePath,goalFilePath] withFileName:@"originalFilePath-goalFilePath"];
    
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        BOOL isDir = NO;
        BOOL existed = [fileManager fileExistsAtPath:tempVedioPath isDirectory:&isDir];
    
        if(!existed){
            BOOL isCreateSeccessful =  [fileManager createDirectoryAtPath:tempVedioPath withIntermediateDirectories:YES attributes:nil error:nil];
            [self wqWriteData:[NSString stringWithFormat:@"createDirectoryAtPath--isCreateSeccessful====%@",isCreateSeccessful?@"YES":@"NO"] withFileName:@"createDirectoryAtPath6666gerfdgdfgd"];
        }
        else{
//            [self wqWriteData:@"createDirectoryAtPath====NO" withFileName:@"createDirectoryAtPath"];
        }
    
    
    
        //    //rarFilePath = [rarFilePath stringByAppendingPathComponent:fileNameStr];
        //
        ////    BOOL isSave = [wqfileData writeToFile:rarFilePath atomically:YES];
        //    NSError *error = nil;
        //    BOOL success = [fileManager moveItemAtPath:originalFilePath toPath:goalFilePath error:&error];
        ////    BOOL success = [fileManager copyItemAtPath:originalFilePath toPath:goalFilePath error:&error];
        ////    [fileManager ];
    
        //NSData *data = [NSData dataWithContentsOfFile:tempVedioPath];
    
        //[YSHelp wqWriteData:[NSString stringWithFormat:@"data==%@",data] withFileName:@"datadddd"];
    
        NSString *wqSaveFilelPathStr = [tempVedioPath stringByAppendingPathComponent:fileNameStr];
        [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStrhhhhhh==%@",wqSaveFilelPathStr] withFileName:@"wqSaveFilelPathStrdfhrt567657765756"];
        BOOL success = [fData writeToFile:wqSaveFilelPathStr atomically:YES];
    
        if (success) {
//            [self wqWriteData:@"writeToFile====YES" withFileName:@"writeToFile"];
            //        [self wqWriteData:@"文件移动成功" withFileName:@"moveItemAtPath"];
            NSError *error = nil;
            //BOOL wqremoveStat = [fileManager removeItemAtPath:originalFilePath error:&error];
            //[fileManager removeItemAtPath:filePathStr error:&error];
    
            [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStr==%@",wqSaveFilelPathStr] withFileName:@"wquniAppDownloadFileData--wqSaveFilelPathStr--111166"];
    
            if(wqSaveFilelPathStr.length>8){
                NSString *wqFristStr = [wqSaveFilelPathStr substringToIndex:8];
                if(![wqFristStr isEqualToString:@"file:///"]){
                    wqSaveFilelPathStr = [NSString stringWithFormat:@"file://%@",wqSaveFilelPathStr];
                }
            }
    
             [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStr==%@",wqSaveFilelPathStr] withFileName:@"wquniAppDownloadFileData--wqSaveFilelPathStr--222111fghfghfhf"];
    
    
    
            return wqSaveFilelPathStr;
    
        } else {
            // 处理错误
            [self wqWriteData:@"writeToFile====NO" withFileName:@"writeToFilefghfhfgh"];
    
            return @"";
        }
        
}

#pragma mark 移动文件到uniapp公共目录

/**
 * originalStr
 */
+ (NSString *)bossIPMoveVedioToPublickDirWithOriginalStr:(NSString *)originalStr{
    // withGoalFileDirStr:(NSString *)goalFileDirStr


 
    NSString *goalFileDirStr = @"/Pandora/apps/__UNI__7F36DC7/www/xsLBVedioDir/";
   
    NSString *fileNameStr = [originalStr lastPathComponent];// 包含后缀

    
//     NSArray *cachePath= NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//     NSString *cacheDir = [cachePath objectAtIndex:0];
    
    NSString *tempString = NSTemporaryDirectory();
     NSString *tempVedioPath = [NSString stringWithFormat:@"%@videos/%@",tempString,fileNameStr];
    [self wqWriteData:[NSString stringWithFormat:@"tempVedioPath==%@",tempVedioPath] withFileName:@"tempVedioPathfhgfghf"];
    
    
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    //
    //NSString * originalFilePath = tempVedioPath;//originalStr;
    
    NSString * goalFilePath = [docsdir stringByAppendingPathComponent:goalFileDirStr];//将需要创建的串拼接到后面
    
    [self wqWriteData:[NSString stringWithFormat:@"originalFilePath==%@      goalFilePath==%@",tempVedioPath,goalFilePath] withFileName:@"originalFilePath-goalFilePathsdgsgsdgg"];
    
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:goalFilePath isDirectory:&isDir];
    
    if(!existed){
        BOOL isCreateSeccessful =  [fileManager createDirectoryAtPath:goalFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        [self wqWriteData:[NSString stringWithFormat:@"createDirectoryAtPath--isCreateSeccessful====%@",isCreateSeccessful?@"YES":@"NO"] withFileName:@"createDirectoryAtPath3ertgfdfgdf"];
    }
    else{
        [self wqWriteData:@"createDirectoryAtPath====NO" withFileName:@"createDirectoryAtPathsdgerrdregtert"];
    }
    
    
    
    //    //rarFilePath = [rarFilePath stringByAppendingPathComponent:fileNameStr];
    //
    ////    BOOL isSave = [wqfileData writeToFile:rarFilePath atomically:YES];
    //    NSError *error = nil;
    //    BOOL success = [fileManager moveItemAtPath:originalFilePath toPath:goalFilePath error:&error];
    ////    BOOL success = [fileManager copyItemAtPath:originalFilePath toPath:goalFilePath error:&error];
    ////    [fileManager ];
    
    NSData *data = [NSData dataWithContentsOfFile:tempVedioPath];
    
    [YSHelp wqWriteData:[NSString stringWithFormat:@"data==%@",data] withFileName:@"datadddd"];
    
    NSString *wqSaveFilelPathStr = [goalFilePath stringByAppendingPathComponent:fileNameStr];
    [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStr==%@",wqSaveFilelPathStr] withFileName:@"wqSaveFilelPathStrregedfgfh"];
    BOOL success = [data writeToFile:wqSaveFilelPathStr atomically:YES];
    
    if (success) {
        [self wqWriteData:@"writeToFile====YES" withFileName:@"writeToFile"];
        //        [self wqWriteData:@"文件移动成功" withFileName:@"moveItemAtPath"];
        NSError *error = nil;
        BOOL wqremoveStat = [fileManager removeItemAtPath:tempVedioPath error:&error];
       
        
        [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStr==%@",wqSaveFilelPathStr] withFileName:@"wquniAppDownloadFileData--wqSaveFilelPathStr--1111sdsdg"];

        if(wqSaveFilelPathStr.length>8){
            NSString *wqFristStr = [wqSaveFilelPathStr substringToIndex:8];
            if(![wqFristStr isEqualToString:@"file:///"]){
                wqSaveFilelPathStr = [NSString stringWithFormat:@"file://%@",wqSaveFilelPathStr];
            }
        }

         [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStr==%@",wqSaveFilelPathStr] withFileName:@"wquniAppDownloadFileData--wqSaveFilelPathStr--222111dfgd"];
         
         
         
        return wqSaveFilelPathStr;
        
    } else {
        // 处理错误
        [self wqWriteData:@"writeToFile====NO" withFileName:@"writeToFile"];
        
        
        return @"";
    }
    
}



/**
 * 传入 视频文件数据fData   跟视频文件路径
 *  返回写入数据到bossip公共目录的路径
 */
+ (NSString *)bossIpWriteVideoData:(NSData *)fData withVideoFilePath:(NSString *)videoFilePathStr{
    
    
    
        NSString *goalFileDirStr = @"/Pandora/apps/__UNI__7F36DC7/www/xsLBVedioDir/";

        NSString *fileNameStr = [videoFilePathStr lastPathComponent];// 包含后缀
    
    
    //     NSArray *cachePath= NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //     NSString *cacheDir = [cachePath objectAtIndex:0];
    
//        NSString *tempString = NSTemporaryDirectory();
//    //[NSString stringWithFormat:@"%@/xsBossVideos/%@",tempString,fileNameStr]
//         NSString *tempVedioPath = [NSString stringWithFormat:@"%@/xsBossVideos/",tempString];
        //[self wqWriteData:[NSString stringWithFormat:@"tempVedioPath==%@",tempVedioPath] withFileName:@"tempVedioPath"];
    
    
        NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
//        //
//        NSString * originalFilePath = originalStr;
//
        NSString * goalFilePath = [docsdir stringByAppendingPathComponent:goalFileDirStr];//将需要创建的串拼接到后面
//
        [self wqWriteData:[NSString stringWithFormat:@"videoFilePathStr==%@      goalFilePath==%@",videoFilePathStr,goalFilePath] withFileName:@"originalFilePath-goalFilePath999kjjkkk"];
    
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        BOOL isDir = NO;
        BOOL existed = [fileManager fileExistsAtPath:goalFilePath isDirectory:&isDir];
    
        if(!existed){
            BOOL isCreateSeccessful =  [fileManager createDirectoryAtPath:goalFilePath withIntermediateDirectories:YES attributes:nil error:nil];
            [self wqWriteData:[NSString stringWithFormat:@"createDirectoryAtPath--isCreateSeccessful====%@",isCreateSeccessful?@"YES":@"NO"] withFileName:@"createDirectoryAtPath6666gerfdgdfgd--goalFilePathrrr"];
        }
        else{
            [self wqWriteData:@"createDirectoryAtPath====NO" withFileName:@"createDirectoryAtPath--goalFilePathrrr444"];
        }
    
    
    
        //    //rarFilePath = [rarFilePath stringByAppendingPathComponent:fileNameStr];
        //
        ////    BOOL isSave = [wqfileData writeToFile:rarFilePath atomically:YES];
        //    NSError *error = nil;
        //    BOOL success = [fileManager moveItemAtPath:originalFilePath toPath:goalFilePath error:&error];
        ////    BOOL success = [fileManager copyItemAtPath:originalFilePath toPath:goalFilePath error:&error];
        ////    [fileManager ];
    
        //NSData *data = [NSData dataWithContentsOfFile:tempVedioPath];
    
        //[YSHelp wqWriteData:[NSString stringWithFormat:@"data==%@",data] withFileName:@"datadddd"];
    
        NSString *wqSaveFilelPathStr = [goalFilePath stringByAppendingPathComponent:fileNameStr];
        [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStrhhhhhh==%@",wqSaveFilelPathStr] withFileName:@"wqSaveFilelPathStrdfhrt567657765756--video888"];
        BOOL success = [fData writeToFile:wqSaveFilelPathStr atomically:YES];
    
        if (success) {
//            [self wqWriteData:@"writeToFile====YES" withFileName:@"writeToFile"];
            //        [self wqWriteData:@"文件移动成功" withFileName:@"moveItemAtPath"];
            NSError *error = nil;
            //BOOL wqremoveStat = [fileManager removeItemAtPath:originalFilePath error:&error];
            [fileManager removeItemAtPath:videoFilePathStr error:&error];
    
            [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStr==%@",wqSaveFilelPathStr] withFileName:@"wquniAppDownloadFileData--wqSaveFilelPathStr--111166gg"];
    
            if(wqSaveFilelPathStr.length>8){
                NSString *wqFristStr = [wqSaveFilelPathStr substringToIndex:8];
                if(![wqFristStr isEqualToString:@"file:///"]){
                    wqSaveFilelPathStr = [NSString stringWithFormat:@"file://%@",wqSaveFilelPathStr];
                }
            }
    
             [YSHelp wqWriteData:[NSString stringWithFormat:@"wqSaveFilelPathStr==%@",wqSaveFilelPathStr] withFileName:@"wquniAppDownloadFileData--wqSaveFilelPathStr--222111fghfghfhf"];
    
    
    
            return wqSaveFilelPathStr;
    
        } else {
            // 处理错误
            [self wqWriteData:@"writeToFile====NO" withFileName:@"writeToFilefghfhfgh"];
    
            return @"";
        }
        
}
// 获取图片被压缩后的实际大小
+ (CGSize)bossIPGetImageCompressedSizeWithImageView:(UIImageView *)imageView{
    
    //UIImageView *imageView = ...; // 你的UIImageView实例
    UIImage *image = imageView.image;
    CGSize imageSize = image.size;
    CGSize viewSize = imageView.frame.size;

    CGFloat aspectRatio = imageSize.width / imageSize.height;
    CGSize displaySize;

    if (imageView.contentMode == UIViewContentModeScaleAspectFit || imageView.contentMode == UIViewContentModeScaleAspectFill || imageView.contentMode == UIViewContentModeScaleToFill) {
        if (viewSize.width / viewSize.height > aspectRatio) {
            displaySize.width = viewSize.height * aspectRatio;
            displaySize.height = viewSize.height;
        } else {
            displaySize.width = viewSize.width;
            displaySize.height = viewSize.width / aspectRatio;
        }
    } else if (imageView.contentMode == UIViewContentModeScaleToFill) {
        displaySize = viewSize;
    } else {
        displaySize = imageSize;
    }

    CGSize compressedSize;
    compressedSize.width = MIN(imageSize.width, displaySize.width);
    compressedSize.height = MIN(imageSize.height, displaySize.height);

    NSLog(@"图片压缩后的大小： %@", NSStringFromCGSize(compressedSize));
    return compressedSize;
}

@end




